import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCustomCompareEffect } from 'react-use';
import { connect } from 'umi';
import { Button, Form, Select, Spin, Table, Tag } from 'antd';
import classNames from 'classnames';
import { isNil, omitBy, trim } from 'lodash';
import moment from 'moment';

import { defaultFormatResult, useRequest } from '@/hooks';
import OrganizationSelect from '@/components/OrganizationSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import { SearchInput } from '@/components/UserForm';
import { isSuccess } from '@/utils/request';

import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import { cpfSubmissionStatus, cpfSubmissionStatusEnum, jobStatusEnum } from '@/pages/SalaryManage/enum';
import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import SalaryConfigTipPage from '@/pages/SalaryManage/components/SalaryConfigTipPage';
import Search from '@/pages/SalaryManage/components/SuperSearch';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import EmployeeNameWrapper from '@/pages/SalaryManage/components/EmployeeNameWrapper';
import { commonColumn, dateColumn } from '@/pages/SalaryManage/utils/TableUtil';
import { cpfService } from '@/services/salaryManage/salaryCalculateService';
import { gotoCPFSetting } from '@/pages/SalaryManage/utils/pageNavigateUtil';
import InsuranceFundFileRouter from '@/pages/SalaryManage/SalaryCalculate/InsuranceFundFile/components/InsuranceFundFileRouter';
import InsuranceFundFileMenuFilter from '@/pages/SalaryManage/SalaryCalculate/InsuranceFundFile/components/InsuranceFundFileMenuFilter';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';

const namespace = 'insuranceFundFileModel';

// 员工状态枚举
const jobStatusEnumList = jobStatusEnum.list();

const { Option } = Select;

/** 查询条件 */
const SearchWrapper = ({ form, onSearch, organizationCode, wrapperFormRef }) => {
    const { getFieldDecorator } = form;

    useEffect(() => {
        if (wrapperFormRef) {
            wrapperFormRef(form);
        }
    }, [form, wrapperFormRef]);

    return (
        <Search.Wrapper onSearch={onSearch}>
            <TwoColHead
                left={
                    <Search.Commonly>
                        <Search.Item label="状态">
                            {getFieldDecorator('status', { initialValue: jobStatusEnumList[0].value })(
                                <Select style={{ width: '12.875em' }}>
                                    {jobStatusEnumList.map(status => (
                                        <Option key={status.value} value={status.value}>
                                            {jobStatusEnum.getShowName(status.value)}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Search.Item>
                    </Search.Commonly>
                }
                right={
                    <Button type="primary" ghost onClick={() => gotoCPFSetting({ organizationCode })}>
                        公积金档案
                    </Button>
                }
            />
            <Search.More>
                <Search.Item label="姓名">
                    <span>
                        {getFieldDecorator('employeeCode')(
                            <SearchInput
                                params={{
                                    organizationCode
                                }}
                                getData={async params => {
                                    if (!params.organizationCode) {
                                        return [];
                                    }
                                    const employeeResponse = await queryEmployeeList({
                                        organizationCode: params.organizationCode
                                    });
                                    return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                                }}
                                selectProps={{
                                    placeholder: '请输入员工姓名',
                                    allowClear: true
                                }}
                                fieldsName={{
                                    value: 'employeeCode',
                                    title: 'name'
                                }}
                                style={{ width: '12.875em' }}
                            />
                        )}
                    </span>
                </Search.Item>

                <Search.Item label="组织机构">
                    {getFieldDecorator(
                        'departmentCode',
                        {}
                    )(
                        <OrganizationSelect
                            isFunctional
                            extraQuery={{ auditStatus: 2 }}
                            dropdownStyle={{ maxHeight: 350, width: 298, overflow: 'auto' }}
                        />
                    )}
                </Search.Item>
            </Search.More>
        </Search.Wrapper>
    );
};

/** 表格 */
const TableWrapper = ({ columns, dataSource, tablePageChange, pagination }) => (
    <div>
        <Table
            tableLayout="fixed"
            columns={columns}
            rowKey="employeeNo"
            dataSource={dataSource}
            pagination={false}
            scroll={{ x: 'max-content' }}
            bordered
        />
        <Pagination {...pagination} onChange={tablePageChange} />
    </div>
);

const tableColumns = [
    {
        title: <EmployeeNameWrapper
            left={<i className={classNames(salaryStyle.circle, salaryStyle.circleHidden)} />}
            name="姓名"
        />,
        dataIndex: 'name',
        align: 'left',
        fixed: true,
        width: 202,
        render(text, record) {
            let tag = null;
            let circle = (
                <i className={classNames(salaryStyle.circle, salaryStyle.circleHidden)} />
            );
            if (record.cpfSubmissionStatus === cpfSubmissionStatus.JOIN) {
                circle = <i className={salaryStyle.circle} />;
                tag = (
                    <Tag color="orange" className={classNames(salaryStyle.noBorderTag, salaryStyle.mr0)}>
                        {cpfSubmissionStatusEnum.getShowName(cpfSubmissionStatus.JOIN)}
                    </Tag>
                );
            }

            // 已增员状态且为入职日期与当前月份为同一月
            if (record.cpfSubmissionStatus === cpfSubmissionStatus.PAYING &&
                record.startDate && moment().isSame(moment(record.startDate, 'YYYY-MM-DD'), 'month')
            ) {
                circle = <i className={salaryStyle.circle} />;
                tag = (
                    <Tag color="orange" className={classNames(salaryStyle.noBorderTag, salaryStyle.mr0)}>
                        {cpfSubmissionStatusEnum.getShowName(cpfSubmissionStatus.PAYING)}
                    </Tag>
                );
            }

            if (record.cpfSubmissionStatus === cpfSubmissionStatus.STOP) {
                circle = <i className={salaryStyle.circle} />;
                tag = (
                    <Tag color="red" className={classNames(salaryStyle.noBorderTag, salaryStyle.mr0)}>
                        {cpfSubmissionStatusEnum.getShowName(cpfSubmissionStatus.STOP)}
                    </Tag>
                );
            }

            return (
                <EmployeeNameWrapper left={circle} name={text} right={tag} />
            );
        },
        ellipsis: true
    },
    commonColumn({
        title: '工号',
        dataIndex: 'employeeNo',
        align: 'center',
        fixed: true,
        width: 100,
        ellipsis: true
    }),
    commonColumn({
        title: '证件号',
        dataIndex: 'identityidNo',
        align: 'center',
        width: 200,
        ellipsis: true
    }),
    dateColumn({
        title: '入职日期',
        dataIndex: 'startDate',
        ellipsis: true
    }),
    {
        title: '状态',
        dataIndex: 'statusName',
        align: 'center',
        width: 110,
        ellipsis: true
    },
    commonColumn({
        title: '组织机构',
        dataIndex: 'departmentName',
        width: 200,
        ellipsis: true
    }),
    commonColumn({
        title: '身份类型',
        dataIndex: 'singaporeidTypeName',
        width: 200,
        ellipsis: true
    }),
    dateColumn({
        title: 'PR取得时间',
        dataIndex: 'prAcquisitionDate',
        ellipsis: true
    }),
    commonColumn({
        title: 'PR年限',
        dataIndex: 'prIssueYear',
        width: 200,
        ellipsis: true,
        render(text) {
            if (!trim(text) || text < 1) {
                return <EmptyPlaceHolder />
            }

            return `第${text}年`;
        }
    }),
    commonColumn({
        title: 'CPF类型',
        dataIndex: 'cpfPayName',
        width: 200,
        ellipsis: true
    }),
    commonColumn({
        title: '年龄',
        dataIndex: 'age',
        width: 100,
        ellipsis: true
    }),
    commonColumn({
        title: '增减员状态',
        dataIndex: 'cpfSubmissionStatus',
        width: 100,
        ellipsis: true,
        render: text => <EmptyPlaceHolder value={cpfSubmissionStatusEnum.getShowName(text)} />
    })
];

const CPFFile = ({ dispatch, selectOrganizationCode, organizationResponse }) => {
    const formRef = useRef();
    const [searchModel, setSearchModel] = useState({});
    const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });
    const [dataSource, setDataSource] = useState([]);
    const { loading, run: queryCPFEmployeeList } = useRequest(params => cpfService.getCPFEmployeeList(params), {
        ...defaultFormatResult,
        manual: true
    });

    const search = useCallback(
        async pageInfo => {
            // 获取查询条件
            const getSearchCondition = () => ({
                searchModel,
                pagination: pagination || {
                    current: 1,
                    pageSize: 10
                }
            });

            const getPostData = searchCondition => {
                const { current: pageNo, pageSize } = searchCondition.pagination;
                const { ...postModel } = searchCondition.searchModel;

                const page = { pageNo, pageSize };

                return { ...page, ...postModel, organizationCode: selectOrganizationCode };
            };

            const searchCondition = getSearchCondition();
            if (pageInfo) {
                searchCondition.pagination = { ...searchCondition.pagination, ...omitBy(pageInfo, isNil) };
            } else {
                searchCondition.pagination.current = 1;
            }
            const responseData = await queryCPFEmployeeList(getPostData(searchCondition));
            if (responseData) {
                const { size: pageSize, total, current, records } = responseData;
                setDataSource(records);
                setPagination({
                    ...pagination,
                    pageSize: pageSize || 10,
                    current: current || 1,
                    total
                });
            }
        },
        [pagination, queryCPFEmployeeList, searchModel, selectOrganizationCode]
    );

    // 页码变化
    const tablePageChange = useCallback(
        ({ current, pageSize }) => {
            search({
                current,
                pageSize
            });
        },
        [search]
    );

    useCustomCompareEffect(
        () => {
            if (selectOrganizationCode) {
                if (formRef.current) {
                    // 重置表单数据并更新model
                    formRef.current.resetFields();
                    setSearchModel(formRef.current.getFieldsValue());
                }
                search();
            }
        },
        [selectOrganizationCode, search],
        ([prevSelectOrganizationCode], [nextSelectOrganizationCode]) =>
            prevSelectOrganizationCode === nextSelectOrganizationCode
    );

    const EnhancedSearchWrapper = useMemo(
        () =>
            Form.create({
                onValuesChange: (props, changedValues, allValues) => {
                    setSearchModel(allValues);
                }
            })(SearchWrapper),
        []
    );

    const handleOrganizationChange = useCallback(
        value => {
            if (selectOrganizationCode !== value) {
                dispatch({
                    type: `${namespace}/setMultiStore`,
                    payload: {
                        selectOrganizationCode: value,
                        countryNameCode: null
                    }
                });
            }
        },
        [selectOrganizationCode]
    );

    return (
        <PageHeaderWrapper type="success">
            <BaseSettingProvider organizationCode={selectOrganizationCode}>
                <InsuranceFundFileMenuFilter>
                    <InsuranceFundFileRouter
                        type="insuranceFundFile"
                        extraButton={
                            <div style={{ display: 'flex' }}>
                                <OrganizationSelect
                                    isStrictly
                                    isNeedPermission
                                    style={{ width: 220 }}
                                    onChange={handleOrganizationChange}
                                    value={selectOrganizationCode}
                                    allowClear={false}
                                    dropdownMatchSelectWidth
                                    treeDataFromProp
                                    treeDataList={organizationResponse}
                                />
                            </div>
                        }
                    >
                        <SalaryConfigTipPage organizationCode={selectOrganizationCode}>
                            <div className={salaryStyle.salaryWrapper}>
                                <Spin spinning={loading}>
                                    <EnhancedSearchWrapper
                                        onSearch={search}
                                        organizationCode={selectOrganizationCode}
                                        wrapperFormRef={form => {
                                            formRef.current = form;
                                        }}
                                    />
                                    <TableWrapper
                                        columns={tableColumns}
                                        dataSource={dataSource}
                                        tablePageChange={tablePageChange}
                                        pagination={pagination}
                                    />
                                </Spin>
                            </div>
                        </SalaryConfigTipPage>
                    </InsuranceFundFileRouter>
                </InsuranceFundFileMenuFilter>
            </BaseSettingProvider>
        </PageHeaderWrapper>
    );
};

export default connect(({ insuranceFundFileModel }) => ({
    selectOrganizationCode: insuranceFundFileModel.selectOrganizationCode,
    organizationResponse: insuranceFundFileModel.organizationResponse
}))(CPFFile);
